package com.price.httplib.status

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.util.Log
import com.price.common.extend.register

class NetStateChangeReceiver: BroadcastReceiver() {
    private object InstanceHolder {
        public val INSTANCE = NetStateChangeReceiver()
    }

    private val mObservers: ArrayList<NetStateChangeObserver> = ArrayList()

    override fun onReceive(context: Context, intent: Intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
            val networkType = NetworkUtil.getNetworkType(context)
            Log.i("NetStateChangeReceiver", networkType.toString())
            notifyObservers(networkType)
        }
    }

    fun registerObserver(context: Context, observer: NetStateChangeObserver?) {
        val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
        context.register(InstanceHolder.INSTANCE, intentFilter, 0)
        if (observer == null) {
            return
        }
        if (!InstanceHolder.INSTANCE.mObservers.contains(observer)) {
            InstanceHolder.INSTANCE.mObservers.add(observer)
        }
    }

    fun unRegisterObserver(context: Context, observer: NetStateChangeObserver?) {
        context.unregisterReceiver(InstanceHolder.INSTANCE)
        if (observer == null) {
            return
        }
        if (InstanceHolder.INSTANCE.mObservers == null) {
            return
        }
        InstanceHolder.INSTANCE.mObservers.remove(observer)
    }

    private fun notifyObservers(networkType: NetworkType) {
        if (networkType == NetworkType.NETWORK_NO) {
            for (observer in mObservers) {
                observer.onNetDisconnected()
            }
        } else {
            for (observer in mObservers) {
                observer.onNetConnected(networkType)
            }
        }
    }
}